package com.seaboxdata.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @create 2021-05-27 19:10
 **/
public class HttpUtils {

    public static String post(String url, Map<String, String> paramsMap,Map<String,String> headersMap) throws Exception {
        HttpClient client = new SSLClient();
        HttpPost request = new HttpPost(new URI(url));
        for (Map.Entry<String, String> headerEntry : headersMap.entrySet()) {
            request.addHeader(new BasicHeader(headerEntry.getKey(), headerEntry.getValue()));
        }
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> paramEntry : paramsMap.entrySet()) {
            paramsList.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
        }
        request.setEntity(new UrlEncodedFormEntity(paramsList, "utf-8"));
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } else {
            throw new Exception("post " + url + " get data error");
        }
    }

}
